package com.deltabot.master.webserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/*
This responder object will have a new instance created for each user that connects,
will then flush out our data,
and dispose itself when done
*/

public class responder extends Thread {
      public Socket remoteClient;

    public responder(Socket remoteSock){
        this.remoteClient = remoteSock;
    }

    public void run(){

        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(remoteClient.getInputStream()));
            PrintWriter out = new PrintWriter(remoteClient.getOutputStream());

            try{
                //Get the client headers, we might be able to use these later for statistics
                String Headers = "";
                String ClientHeaders = ".";   //String used for reading the headers and printing them out
                while(!ClientHeaders.equals("")){
                    ClientHeaders = in.readLine();
                    Headers +=  ClientHeaders + "\n";
                }
                //Now the 'Headers' string contains everything and could be used
                String SockHeaders[] = Headers.split("\n");

                for (String header : SockHeaders){
                    //This will loop all of the headers so they can be collected
                    //System.out.println(header);
                }
            } catch (Exception e){
             //System.out.println("Error while parsing client headers");
            }

            //Now we should create our response
            //Start with the headers
            out.println("HTTP/1.0 200 OK");
            out.println("Cache-Control: no-cache"); //Disable the cache in the web browser
            out.println("Server: deltaBot-MasterServer");
            out.println("Connection: close");
            out.println(""); //A blank line indicates the end of our headers, we can now write our html code

            out.print(htmlHandler.getIndexPage());

            out.flush();

            remoteClient.close();
            currentThread().stop();   //Obsolete code, but for now it should do fine
            this.destroy();
        } catch (IOException e) {
            System.out.println("Error: " + e);
        }

    }

}
